import socket
import concurrent.futures
import logging

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

# 处理客户端连接的函数
def handle_client(client_socket, client_address):
    try:
        logging.info(f"客户端 {client_address[0]}:{client_address[1]} 已连接")
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            logging.info(f"来自客户端 {client_address[0]}:{client_address[1]} 的消息: {data.decode('utf-8')}")

            # 服务器处理数据逻辑（范例置空）
            response = "服务器已收到您的消息"
            client_socket.send(response.encode('utf-8'))
    except Exception as e:
        logging.error(f"处理客户端 {client_address[0]}:{client_address[1]} 的连接时发生异常: {str(e)}")
    finally:
        logging.info(f"关闭客户端 {client_address[0]}:{client_address[1]} 的连接")
        client_socket.close()

# 处理拒绝连接的函数
def handle_rejection(client_socket):
    try:
        logging.warning("客户端连接数已达上限，拒绝新的连接请求")
        client_socket.send("服务器连接数已达上限，请稍后再试".encode('utf-8'))
    except Exception as e:
        logging.error(f"拒绝连接时发生异常: {str(e)}")
    finally:
        client_socket.close()

def main():
    server_host = '192.168.148.179'  # 服务器主机
    server_port = 18011  # 服务器端口
    max_clients = 5  # 最大客户端连接数
    active_connections = 0  # 当前活动的客户端连接数

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((server_host, server_port))
    server.listen(max_clients)  # 最多允许max_clients个客户端排队等待连接

    logging.info(f"等待客户端连接在 {server_host}:{server_port}...")

    # 创建一个线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_clients) as executor:
        while True:
            client_socket, client_address = server.accept()
            active_connections += 1

            if active_connections <= max_clients:
                # 如果还有空余连接空间，则正常处理客户端连接
                executor.submit(handle_client, client_socket, client_address)
            else:
                # 如果连接数已经达到上限，则启动一个单独的线程来处理拒绝连接
                handle_rejection(client_socket)
                active_connections -= 1

if __name__ == "__main__":
    main()